<?php

namespace App\Http\Controllers\Service;

use App\Exceptions\GeneralException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Station\Network\NetworkQuery;
use App\Http\Requests\Station\Network\RelationNetwork;
use App\Http\Requests\Station\Network\StationUpdate;
use App\Http\Requests\Station\Network\ShowRequest;
use App\Http\Requests\Station\Network\QueryResource;
use App\Http\Requests\Station\Network\NetworkCreate;
use App\Http\Requests\Station\Network\NetworkUpdate;
use App\Http\Requests\Station\Network\NetworkDestroy;
use App\Models\Network;
use App\Models\NetworkAdmin;
use App\Models\NetworkExpress;
use App\Repositories\NetworkRepository;
use App\Repositories\UserLogRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class NetworkController extends Controller
{
    //默认密码
    const BASE_PASSWORD = '123456';
    const NETWORK_STATUS = [
        0 => '申请开通',
        1 => '运营中',
        2 => '已停业',
    ];
    protected $networkRepository;
    protected $userLogRepository;

    /**
     * NetworksController constructor.
     * @param NetworkRepository $networkRepository
     * @param UserLogRepository $userLogRepository
     */
    public function __construct(
        NetworkRepository $networkRepository,
        UserLogRepository $userLogRepository
    )
    {
        $this->networkRepository = $networkRepository;
        $this->userLogRepository = $userLogRepository;
    }

    /**
     * 获取网点列表资源列表
     *
     * Date: 2018/05/10
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function index(QueryResource $request)
    {
        $limit = $request->get('paginate', false);
        if ($limit == null) {
            $limit = false;
        }
        $admins = Auth::guard('station')->user();
        $service_id = $admins->service_id;
        $networks = $this->networkRepository->getRelationNetworks($service_id, $limit);
        return success($networks);
    }

    /**
     * 获取网点详情
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param ShowRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(ShowRequest $request, Network $network)
    {
        $admins = Auth::guard('station')->user();
        $service_id = $admins->service_id;
        $networks = $this->networkRepository->getNetworkDetails($network->id, $service_id);
        return success($networks);
    }


    /**
     * 创建网点
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param NetworkCreate $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function store(NetworkCreate $request)
    {
        $attributes = $this->extractInputFromRules($request, $request->rules());
        $attributes['status'] = 0;//申请网点
        DB::beginTransaction();
        try {
            unset($attributes['password']);
            $networks = $this->networkRepository->create($attributes);
            //创建网点管理员账户
            $adminUser = new NetworkAdmin();
            $adminUser->name = $request->name;
            $adminUser->phone = $request->phone;
            $adminUser->password = $request->password;
            $adminUser->network_id = $networks->id;
            $adminUser->status = 0;//未启用，申请中
            $adminUser->save();
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            dd($ex);
            throw new GeneralException('未知错误', 500);
        }
        //记录日志
        $admin = Auth::guard('station')->user();
        $uid = $admin->id;
        $service_id = $admin->service_id;
        $name = $admin->name;
        $operation = '创建了[' . $networks->designation . ']网点';
        $history = $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 3;
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return stored($networks);
    }

    /**
     * 检测手机号码是否存在
     *
     * Date: 2018/06/10
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function existence(Request $request)
    {
        $this->validate($request, [
            'phone' => ['required', 'regex:/^(1[3456789])\d{9}$/', 'unique:service,phone']
        ], [
            'phone.required' => '请输入手机号码',
            'phone.regex' => '您输入的手机号码有误',
            'phone.unique' => '您输入的手机号码已存在'
        ]);
        return message('可以注册');
    }

    /**
     * 关联网点
     *
     * Date: 2018/06/12
     * @author Tenny
     * @param RelationNetwork $request
     * @return \Illuminate\Http\JsonResponse
     * @throws  GeneralException
     */
    public function relation(RelationNetwork $request)
    {
        $attributes = $this->extractInputFromRules($request, $request->rules());
        $admin = Auth::guard('station')->user();
        $uid = $admin->id;
        $service_id = $admin->service_id;
        $name = $admin->name;
        DB::beginTransaction();
        try {
            //判断是否可以关联
            $networks = $this->networkRepository->isRelation($service_id, $attributes['network_id']);
            if ($networks) {
                throw new GeneralException('已经关联过改物流公司的网点', 403);
            } else {
                $networkExpress = new NetworkExpress;
                $networkExpress->service_id = $service_id;
                $networkExpress->network_id = $attributes['network_id'];
                $networkExpress->credit = $attributes['credit'];
                $networkExpress->unit_price = $attributes['unit_price'];
                $networkExpress->save();
            }
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            throw new GeneralException('未知错误', 500);
        }
        //记录日志
        $operation = '关联了[' . $attributes['network_id'] . ']网点';
        $history = $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 3;
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return stored([]);
    }

    /**
     * 修改网点关联网点信用
     *
     * Date: 2018/06/12
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws  GeneralException
     */
    public function updateNetworkStation(Request $request)
    {
        $this->validate($request, [
            'network_id' => 'required|integer',
            'credit' => ['nullable', 'regex:/^[0-9]+(.[0-9]{1,2})?$/'],
            'unit_price' => ['nullable', 'regex:/^[0-9]+(.[0-9]{1,2})?$/'],
        ], [
            'network_id.required' => '请选择网点',
            'network_id.integer' => '请选择正确的网点',
            'credit.regex' => '请输入正确的信用',
            'unit_price.regex' => '请输入正确的单价',
        ]);
        $network_id = $request->get('network_id', false);
        $networkStations = array_filter($request->only([
            'credit',
            'unit_price',
        ]), function ($value) {
            if ($value === null || $value === '') {
                return false;
            } else {
                return true;
            }
        });
        $admin = Auth::guard('station')->user();
        $uid = $admin->id;
        $service_id = $admin->service_id;
        $name = $admin->name;
        $networkStation = NetworkExpress::where('network_express.network_id', '=', $network_id)
            ->where('network_express.service_id', '=', $service_id)
            ->with(['services', 'network'])
            ->first();
        $networkArr = [];
        if ($networkStation) {
            if ($networkStation->credit && array_key_exists('credit', $networkStations)) {
                if ($networkStations['credit'] !== $networkStation->credit) {
                    $networkArr['credit'] = $networkStation->credit;
                }
            }
            if ($networkStation->unit_price && array_key_exists('unit_price', $networkStations)) {
                if ($networkStations['unit_price'] !== $networkStation->unit_price) {
                    $networkArr['unit_price'] = $networkStation->unit_price;
                }
            }
        } else {
            return failed('找不到该关联关系', 400);
        }
        $result = [];
        if (count($networkArr) > 0) {
            $networkStation->update($networkStations);
            //记录日志
            $operation = '更新了关联网点[' . $networkStation->id . ']';
            $history = json_encode($networkArr, true);
            $actuality = json_encode($networkStations, true);
            $order_id = 0;//非订单
            $ip = $request->getClientIp();
            $type = 3;
            $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
            $result = NetworkExpress::where('id', '=', $networkStation->id)
                ->with(["services",
                    "network" => function ($query) {
                        $query->with('express');
                    }
                ])
                ->first();
        }
        return success($result);
    }

    /**
     * 解除关联网点
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroyRelation(Request $request)
    {
        $id = $request->get('id', false);
        if (!$id || $id == 0) {
            return failed('请上传正确的id', 422);
        }
        $admin = Auth::guard('station')->user();
        $uid = $admin->id;
        $service_id = $admin->service_id;
        $name = $admin->name;
        $networkExpress = NetworkExpress::where('id', '=', $id)
            ->with(['services', 'network'])
            ->first();
        if ($networkExpress) {
            $networkExpress->delete();
        } else {
            return failed('找不到该关联关系', 403);
        }
        //记录日志
        $operation = '解除除了站点[' . $networkExpress->services->designation . ']与网点[' . $networkExpress->network->designation . ']的关联';
        $history = null;
        $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 3;
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return deleted();
    }

    /**
     * 获取所有未关联网点列表资源列表
     *
     * Date: 2018/05/10
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function all(QueryResource $request)
    {
        $province_id = $request->get('province_id', false);
        $city_id = $request->get('city_id', false);
        $district_id = $request->get('district_id', false);
        $where = array_filter([
            'province_id' => $province_id,
            'city_id' => $city_id,
            'district_id' => $district_id,
        ], function ($value) {
            if ($value === null || $value === '') {
                return false;
            } else {
                return true;
            }
        });
        $admin = Auth::guard('station')->user();
        $service_id = $admin->service_id;
        $networks = $this->networkRepository->getSelectNetworks($where, $service_id);
        return success($networks);
    }
}
